import { customRef, inject, ref, watch } from "vue";
import { FormContextKey, FormContextOptions } from "../Form";
import { FormItemContextKey, FormItemContextProps } from "../FormItem";

export default function formFieldRef<T> (props, emit, defaultValue?: T) {
    const value = ref<T>(props.modelValue ?? defaultValue);
    const ctx: FormContextOptions = inject(FormContextKey, null);
    const formItemCtx: FormItemContextProps = inject(FormItemContextKey, null);
    const name = props.name || formItemCtx?.name;
    watch(() => props.modelValue, (val) => {
        value.value = val;
    });
    return customRef((track, trigger) => {
        return {
            get () {
                track();
                return value.value;
            },
            set (newValue) {
                value.value = newValue;
                emit('update:modelValue', newValue);
                if (props.asFormField !== false) {
                    ctx?.onChange(name, newValue);
                }
                trigger();
            }
        };
    });
}
